﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Clinica_Frba
{
    public partial class BuscarAgenda : Form
    {
        public bool baja = false;
        public bool pedirTurno = false;
        public bool cancelTurno = false;
        bool seleccionar = false;
        Conexion sql = Conexion.getInstance();
        Utility util = Utility.getInstance();
        public int id_Medico = 0;
        int codDia = 0;
        string agendaSelec;
        string[] tablaIdDias = { "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
        
        public BuscarAgenda()
        {
            InitializeComponent();
        }

        public bool searchAgenda(int idMed, out int id_agenda, out int cod_dia)
        {
            id_Medico = idMed;
            this.pedirTurno = true;
            this.ShowDialog();

            if (agendaSelec != null && agendaSelec.Length > 0)
            {
                id_agenda = Convert.ToInt32(agendaSelec);
                cod_dia = codDia + 1;
                return true;
            }

            id_agenda = 0;
            cod_dia = 0;
            return false;
        }

        public bool searchAgenda(int idMed, out int id_agenda)
        {
            id_Medico = idMed;
            this.cancelTurno = true;
            this.pedirTurno = true;
            this.ShowDialog();

            if (agendaSelec != null && agendaSelec.Length > 0 && seleccionar)
            {
                id_agenda = Convert.ToInt32(agendaSelec);
                return true;
            }

            id_agenda = -1;
            return false;
        }

        private void BuscarAgenda_Load(object sender, EventArgs e)
        {
            
            this.agendasGrid.CellClick += new DataGridViewCellEventHandler(agendasGrid_CellClick);
            DataGridViewTextBoxColumn newColumn = new DataGridViewTextBoxColumn();
            agendasGrid.Visible = true;
            horariosGrid.Visible = true;

            if (pedirTurno)
            {
                agendasGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                buttonLimpiar.Text = "Seleccionar";
                this.buttonLimpiar.Click -= new System.EventHandler(this.buttonLimpiar_Click);
                this.buttonLimpiar.Click += new System.EventHandler(this.seleccionarDia_Click);
            }

            if (util.getIdRol() == 3)
            {
                user.Text = util.getUserName();
                buttonBuscarMed.Visible = false;
                if (!pedirTurno)
                    buttonLimpiar.Visible = false;
                loadProfesional();
            }
            else
            {
                    if (id_Medico > 0)
                    {
                        loadProfesional();
                        buttonBuscarMed.Visible = false;
                    }
                    /*if (util.getIdRol() == 1)
                    {
                        agendasGrid.Columns.RemoveAt(4);
                    }*/
            }

            if (!this.baja)
            {
                agendasGrid.Columns.Remove(agendasGrid.Columns["EliminarAgenda"]);
            }

            newColumn.HeaderText = "Dia";
            newColumn.Name = "Dia";
            newColumn.ReadOnly = true;
            newColumn.Width = 75;
            if (!horariosGrid.Columns.Contains(newColumn))
            {
                this.horariosGrid.Columns.Insert(0, newColumn);
            }
            
        }

        void agendasGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 0 && baja)
                {
                    agendaSelec = Convert.ToString(agendasGrid["IdAgendaColumn", e.RowIndex].Value);
                    loadHorarios();
                }
                if (e.ColumnIndex == 0 && !baja)
                {
                    agendaSelec = Convert.ToString(agendasGrid["IdAgendaColumn", e.RowIndex].Value);
                    loadHorarios();
                }

                if (baja && e.ColumnIndex == 1)
                {
                    Decision decision = new Decision();
                    decision.Text = "¿Está seguro?";
                    decision.label1.Text = "¿Desea dar de baja la agenda?";
                    decision.ShowDialog();

                    if (decision.confirmar)
                    {
                        try
                        {
                        /*darBajaDias(Convert.ToInt32(agendaSelec));*/
                        cancelarTurnos(Convert.ToDateTime(agendasGrid.Rows[e.RowIndex].Cells[3].Value), Convert.ToDateTime(agendasGrid.Rows[e.RowIndex].Cells[4].Value));

                        SqlCommand darBaja;
                        darBaja = new SqlCommand("UPDATE b_sharp.AgendaProfesional SET bajaLogica = 'S' WHERE id_medico = @idMed AND id_agenda = @idAgenda;", sql.openCon());
                        darBaja.Parameters.AddWithValue("@idAgenda", agendasGrid.Rows[e.RowIndex].Cells[2].Value);
                        darBaja.Parameters.AddWithValue("@idMed", id_Medico);
                        darBaja.ExecuteNonQuery();

                        MessageBox.Show("La agenda se ha eliminado con éxito");
                        buttonLimpiar_Click(this, null);
                        
                        }
                        catch (SqlException)
                        {
                            MessageBox.Show("Error en las consultas");
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error. Intente nuevamente");
            }
        }

        void cancelarTurnos(DateTime fechaI, DateTime fechaF)
        {
                SqlCommand cancelar = new SqlCommand
                           ("INSERT INTO b_sharp.Cancelaciones " +
                            "SELECT Tu.Turno_Numero, '2', 'Se cancela la agenda del médico' " +
                            "FROM b_sharp.Turnos as Tu " +
                            "WHERE Tu.Turno_Fecha between @fechaInicio and @fechaFin " +
                            "AND Tu.Medico_ID = @idMed " +
                            "AND NOT EXISTS (SELECT * FROM b_sharp.Cancelaciones WHERE Turno_Numero = Tu.Turno_Numero);", sql.openCon());
                cancelar.Parameters.AddWithValue("@fechaInicio", fechaI);
                cancelar.Parameters.AddWithValue("@fechaFin", fechaF);
                cancelar.Parameters.AddWithValue("@idMed", id_Medico); 
                cancelar.ExecuteNonQuery();
                MessageBox.Show("Turnos cancelados");

        }

       /* private void darBajaDias(int id_agenda)
        {
                SqlCommand darBajaDias;
                darBajaDias = new SqlCommand("UPDATE b_sharp.AgendaProfHorarios SET WHERE id_agenda = @idAgenda;", sql.openCon());
                darBajaDias.Parameters.AddWithValue("@idAgenda", id_agenda);
                darBajaDias.ExecuteNonQuery();
        }*/


        private void loadProfesional()
        {
            try
            {
                string consulta = "select Me.id_usuario, Me.Medico_Nombre, Me.Medico_Apellido, " +
                "Me.Medico_Num_Doc, Me.Medico_Tipo_Doc, Me.Medico_Mail, Me.Medico_Matricula, Me.id_medico FROM b_sharp.Medicos as Me ";
                
                if (id_Medico == 0)
                    consulta += "WHERE Me.id_usuario = '" + util.getUserName() + "';";
                else
                    consulta += "WHERE Me.id_medico = " + id_Medico + ";";

                SqlDataReader reader = sql.execQuery(consulta);

                reader.Read();
                user.Text = reader.GetValue(0).ToString();
                medicoNom.Text = reader.GetValue(1).ToString();
                medicoApe.Text = reader.GetValue(2).ToString();
                nroDoc.Text = reader.GetValue(3).ToString();
                tipoDoc.Text = reader.GetValue(4).ToString();
                mail.Text = reader.GetValue(5).ToString();
                matricula.Text = reader.GetValue(6).ToString();
                id_Medico = reader.GetInt32(7);
                IdProfesional.Text = Convert.ToString(id_Medico);
                reader.Close();
                /*buttonBuscar.Enabled = false;*/
                loadAgendaGrid();
            }
            catch (SqlException)
            {
                MessageBox.Show("Error en la consulta");
                this.Close();
            }

        }

        private void loadAgendaGrid()
        {
            try
            {
                string qSelect, qFrom, qWhere, query;
                SqlDataAdapter adapter;
                DataTable table = new DataTable();

                qSelect = "SELECT ag.id_agenda, ag.fechaInicio, ag.fechaFin ";
                qFrom = "FROM b_sharp.AgendaProfesional ag ";
                qWhere = "WHERE ag.id_medico = " + id_Medico + " AND ag.bajaLogica = 'N'";

                query = qSelect + qFrom + qWhere + ";";

                adapter = sql.execQueryGrid(query);
                adapter.Fill(table);
                agendasGrid.DataSource = table;

                horariosGrid.Columns["IdDiaColumn"].Visible = false;
            }
            catch (Exception)
            {
                MessageBox.Show("Error en las consultas");
            }
        }

        private void loadHorarios()
        {
            try
            {
                string qSelect, qFrom, qWhere, query;
                SqlDataAdapter adapter;
                DataTable table = new DataTable();

                qSelect = "SELECT aph.cod_dia, aph.horaInicio, aph.horaFin ";
                qFrom = "FROM b_sharp.AgendaProfHorarios aph ";
                qWhere = "WHERE aph.id_agenda = '" + agendaSelec + "' ";

                query = qSelect + qFrom + qWhere + ";";

                adapter = sql.execQueryGrid(query);
                adapter.Fill(table);

                horariosGrid.DataSource = table;

                for (int i = 0; i < horariosGrid.Rows.Count; i++)
                {
                    int codDia = Convert.ToInt32(horariosGrid[1, i].Value);
                    for (int K = 0; K <= tablaIdDias.Length; K++)
                    {
                        if (codDia == K + 1)
                        {
                            string dia = tablaIdDias[K];
                            horariosGrid[0, i].Value = dia;
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error en la consulta");
            }
        }


        private bool validar()
        {
            return true;
        }

        private void buttonLimpiar_Click(object sender, EventArgs e)
        {
            while (agendasGrid.Rows.Count > 0)
                agendasGrid.Rows.RemoveAt(0);

            while (horariosGrid.Rows.Count > 0)
                horariosGrid.Rows.RemoveAt(0);


            tipoDoc.SelectedItem = " ";

            foreach (Control control in this.Controls)
            {
                if (control.GetType().ToString() == "System.Windows.Forms.TextBox")
                    control.ResetText();

                if (control.GetType().ToString() == "System.Windows.Forms.GroupBox")
                {
                    foreach (Control ctrl in ((System.Windows.Forms.GroupBox)control).Controls)
                    {
                        if (ctrl.GetType().ToString() == "System.Windows.Forms.TextBox")
                            ctrl.ResetText();
                    }
                }
            }

            if (util.getIdRol() == 3)
            {
                loadProfesional();
            }
        }

        private void seleccionarDia_Click(object sender, EventArgs e)
        {
            int i = 0;

            if (cancelTurno)
            {
                if (agendasGrid.SelectedRows.Count > 0)
                {
                    agendaSelec = Convert.ToString(agendasGrid.SelectedRows[0].Cells[1].Value);
                    seleccionar = true;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Debe seleccionar una Agenda", "Error");
                }
                return;
            }

            if (horariosGrid.SelectedRows.Count > 0)
            {
                foreach (string dia in tablaIdDias)
                {
                    if ((string)horariosGrid.SelectedRows[0].Cells[0].Value == dia)
                        codDia = i;

                    i++;
                }

                this.Close();
            }
            else
            {
                MessageBox.Show("Debe seleccionar un dia y horario", "Error");
            }
        }

        private void buttonBuscarMed_Click(object sender, EventArgs e)
        {
            ListaProfesionales medicoForm = new ListaProfesionales();

            id_Medico = medicoForm.searchMedico();

            if (id_Medico != -1)
            {
                IdProfesional.Text = id_Medico.ToString();

                loadProfesional();
            }
        }

    }
}
